package com.gp.shaw.netty.io.im;

import com.alibaba.fastjson.JSON;
import com.gp.shaw.netty.io.im.model.IMMsg;
import com.gp.shaw.netty.io.im.model.IMOperator;
import com.gp.shaw.netty.io.im.model.IMUser;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 消息处理
 * Created by asus on 2018/11/1.
 */
public class IMHandler implements Runnable {
    private Socket socket;
    private UserManager userManager;
    private LinkedBlockingQueue<IMMsg> sendQueue;
    public IMHandler(Socket socket,UserManager userManager,LinkedBlockingQueue<IMMsg> queue ) {
        this.socket =socket;
        this.userManager = userManager;
        this.sendQueue = queue;
    }

    @Override
    public void run() {
        ObjectInputStream is = null;
        //接收消息
        try{
            while(true){
                is = new ObjectInputStream(socket.getInputStream());

                IMMsg msg = (IMMsg)is.readObject();
                IMUser imUser = new IMUser();
                imUser.setId(msg.getSender());
                imUser.setSocket(socket);

                switch (msg.getOperator()) {
                    case IMOperator.LOGIN:
                        userManager.addUser(imUser);
                        break;
                    case IMOperator.LOGOUT:
                        userManager.removeUser(imUser);
                        break;
                    case IMOperator.SEND_PERSON:
                        sendQueue.put(msg);
                        break;
                    case IMOperator.SEND_GROUP:
                        sendQueue.put(msg);
                        break;
                    case IMOperator.ADD_GROUP:
                        userManager.addGroup(msg.getSender(),msg.getContent());
                        break;
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}
